/*
 * @Descripttion: 
 * @version: 
 * @Author: Connor
 * @Date: 2020-09-21 15:32:31
 * @LastEditors: Connor
 * @LastEditTime: 2021-03-26 20:42:31
 */
import * as types from './mutation-types'
import * as constant from '../../common/constant'
import { transform, untransform } from '../../common/uri'
import * as utils from '../../common/utils'
import Vue from 'vue'
import axios from 'axios'

axios.defaults.withCredentials=true;

function loadSource(state, bean, option) {
  Vue.set(state.sources, bean, null);
  var uri = constant.API_SERVER + "/api/entry/source?bean=" + bean;
  if (option) {
    uri += "&option=1";
  }
  axios.post(uri).then(response => {
      Vue.set(state.sources, bean, response.data);
    }, error => {
      console.log(error);
      utils.auth(error);
    }
  );
}

function loadSources(state) {
  if (state.entry.group) {
    for (var i = 0; i < state.entry.group.length; ++i) {
      var row = state.entry.group[i];
      var data = [];
      if (row.card) {
        data = row.card;
      } else if (row.list) {
        data = row.list
      } else if (row.chart) {
        data = row.chart;
      }
      for (var j = 0; j < data.length; ++j) {
        if (state.sources[data[j].source]) {
          return;
        }
        if (row.card) {
          loadSource(state, data[j].source, 1);
        } else {
          loadSource(state, data[j].source);
          if (data[j]['x-source']) {
            loadSource(state, data[j]['x-source']);
          }
        }
      }
    }
  }
  if (state.entry.link) {
    for (var i = 0; i < state.entry.link.length; ++i) {
      loadSource(state, state.entry.link[i]['source']);
    }
  }
}

export default {
  [types.LOAD_BOARD_ENTRY] (state, link) {
    var uri = link;

    uri = untransform(uri);
    if (localStorage['baord_' + uri] && ! constant.DEV_MODE) {
      state.entry = JSON.parse(localStorage['baord_' + uri]);
      loadSources(state);
      return;
    }

    var mainUri = '/api/entry/board?uri=' + uri;

    axios.post(constant.API_SERVER + mainUri).then(response => {
        if (response.data) {
          state.entry = response.data;
          loadSources(state);
          localStorage['baord_' + uri] = JSON.stringify(state.entry);
          utils.storeSource(state.entry.sources, 'baord_' + uri);
        }
      }, error => {
        // error callback
        utils.auth(error)
      }
    );

  },
  [types.LOAD_SOURCE_OPTION] (state, bean) {
    loadSource(state, bean, 1);
  },
  [types.LOAD_SOURCE_OPTIONS] (state, bean) {
    loadSource(state, bean);
  },
};
